package com.aaa.spring.intercept;

import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author ：zhu
 */
@Component("myInterceptor")
public class MyInterceptor  extends HandlerInterceptorAdapter {
    StopWatch stopWatch= new StopWatch();
    /**
     * 类似前置增强处理
     * controller中的方法执行之前使用
     * @param request
     * @param response
     * @param handler
     * @return  如果返回true那么就继续往下走，第一种直接进入到controller的方法中，第二种进入到下一个拦截器
     *  如果返回的是false，直接停止，不仅如此下一个拦截器或者controller中的方法。
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("前置增强处理preHandle");
        //记录方法请求的开始时间
        if(stopWatch==null){
            stopWatch=new StopWatch();
        }
        stopWatch.start();
        return true;
    }
    /**
     * 类似后置增强处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("后置增强处理postHandle");
        stopWatch.stop();
        System.out.println(handler.toString()+"时间花费："+stopWatch.getTotalTimeMillis());
    }
    /**
     * 类似最终增强处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("最终增强处理：afterCompletion");
        stopWatch=null;
    }
}

